package com.qj.sys;

import com.qj.threadpool.utils.CompletableFutureUtils;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@SpringBootTest(classes = {SysApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@Slf4j
public class CompletableFutureTest {

    @Resource(name = "mailThreadPool")
    private ThreadPoolExecutor mailThreadPool;

    @Test
    public void testFuture() {
        // 不超时的情况
        FutureTask futureTask1 = new FutureTask<>(() -> "qiu");
        mailThreadPool.submit(futureTask1);
        String name1 = CompletableFutureUtils.getResult(futureTask1,
                1, TimeUnit.SECONDS, "qiujie", log);
        log.info("MailThreadPoolTest.name:{}", name1);

        // 超时的情况
        FutureTask futureTask2 = new FutureTask<>(() -> {
            Thread.sleep(20000);
            return "jie";
        });
        mailThreadPool.submit(futureTask2);
        String name2 = CompletableFutureUtils.getResult(futureTask2,
                1, TimeUnit.SECONDS, "qiujie", log);
        log.info("MailThreadPoolTest.name:{}", name2);
    }

}